package com.icesoft.system.log;

import com.icesoft.framework.core.base.BaseHandlerInterceptor;
import com.icesoft.framework.core.vo.JsonResult;
import com.icesoft.system.safe.helper.RequestHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@Component
@RequiredArgsConstructor
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class LogRequestInterceptor extends BaseHandlerInterceptor {

	@Override
	public String pathPatten() {
		return "/**";
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		StringBuilder sb = new StringBuilder("\nremote ip:" + RequestHelper.getRemoteIP(request)).append("\n");
		sb.append("请求 url: ").append(request.getRequestURI()).append("\n");
		sb.append("----------request params---------- \n");

		if (request.getMethod().equalsIgnoreCase("GET")) {
			RequestHelper.getRequestParamMap(request).forEach((key, val) -> sb.append(key).append(" = ").append(val).append("\n"));
		}

		log.debug(sb.toString());
		long startTime = System.currentTimeMillis();
		request.setAttribute("requestStartTime", startTime);

		if ("GET".equals(request.getMethod())) {
			return true;
		}
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Class<?> returnType = handlerMethod.getReturnType().getMethod().getReturnType();
		if (returnType.isAssignableFrom(ModelAndView.class)) {
			return true;
		}
		boolean isAjax = RequestHelper.isAjax(request);
		boolean isResp = returnType.isAssignableFrom(JsonResult.class);
		if (isAjax && !isResp) {
			log.debug("{}请求返回值不规范，推荐使用JsonResult做为响应值", request.getRequestURI());
		} else if (isResp && !isAjax) {
			log.debug("请求url:{}的请求头x-requested-with错误：{}，请设置为：XMLHttpRequest", request.getRequestURI(),
					request.getHeader("x-requested-with"));
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		if (!(handler instanceof HandlerMethod) || modelAndView != null) {
			return;
		}
		String url = RequestHelper.getRequestUrl(request);
		long startTime = (Long) request.getAttribute("requestStartTime");

		long executeTime = System.currentTimeMillis() - startTime;
		log.debug("请求:{}，执行时长：{}ms", url, executeTime);
	}
}
